//
//  EditPhotoViewController.m
//  CameraDemo
//
//  Created by xujiangtao on 15/11/11.
//  Copyright © 2015年 xujiangtao. All rights reserved.
//

#import "EditPhotoViewController.h"
#import "ClipView.h"
#import "ResultViewController.h"

@interface EditPhotoViewController ()
{
    UIImageOrientation currentRotate;
}
@property (nonatomic,retain) UIImageView* editImaegView;
@property (nonatomic,retain) ClipView* coverView;
@property (nonatomic,retain) UIImage* transformImage;
@end

@implementation EditPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initInterface];
}
#pragma mark- initData
- (void)initData{
    self.image = [self fixrotation:self.image];
    self.transformImage = self.image;
    currentRotate = UIImageOrientationUp;
}
#pragma mark- initInterface
- (void)initInterface{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.editImaegView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20 - 100)];
    self.editImaegView.image = self.image;
    [self.editImaegView setContentMode:UIViewContentModeScaleAspectFit];
    [self.view addSubview:self.editImaegView];
    self.editImaegView.userInteractionEnabled = YES;
    
    self.coverView = [[ClipView alloc] initWithFrame:self.editImaegView.frame];
    self.coverView.backgroundColor = [UIColor clearColor];
    self.coverView.opaque = NO;
    self.coverView.userInteractionEnabled = YES;
    self.coverView.parentView = self.view;
    [self.view addSubview:self.coverView];
    [self.coverView setUserInteractionEnabled:YES];
    
    UIView* toolBarView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 100, self.view.bounds.size.width, 100)];
    [toolBarView setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:toolBarView];
    
    //重拍
    UIButton* reTakeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [reTakeBtn setFrame:CGRectMake(10, 40, 100, 40)];
    [reTakeBtn setTitle:@"重拍" forState:UIControlStateNormal];
    [toolBarView addSubview:reTakeBtn];
    [reTakeBtn addTarget:self action:@selector(clickReTakeBtn) forControlEvents:UIControlEventTouchUpInside];
    
    //确定
    UIButton* okBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [okBtn setFrame:CGRectMake(self.view.bounds.size.width - 10 - 100, 40, 100, 40)];
    [okBtn setTitle:@"确定" forState:UIControlStateNormal];
    [toolBarView addSubview:okBtn];
    [okBtn addTarget:self action:@selector(clickOkBtn) forControlEvents:UIControlEventTouchUpInside];
    
    //旋转
    UIButton* rotateBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [rotateBtn setFrame:CGRectMake((self.view.bounds.size.width - 100) / 2, 40, 100, 40)];
    [rotateBtn setTitle:@"旋转" forState:UIControlStateNormal];
    [toolBarView addSubview:rotateBtn];
    
    [rotateBtn addTarget:self action:@selector(clickRotateBtn) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark- Gesture
- (void)handlePanGesture:(UIPanGestureRecognizer *)gesture{
    NSLog(@"controller pan === ");
}
#pragma mark- Click
- (void)clickReTakeBtn{
    [self.navigationController popViewControllerAnimated:NO];
}
- (void)clickOkBtn{
    ResultViewController* resultVC = [[ResultViewController alloc] init];
//    resultVC.resultImage = [self takeScreenShot:self.editImaegView withRect:self.coverView.holeRect];
    CGFloat scale = (CGFloat)self.transformImage.size.width / self.editImaegView.frame.size.width;
    
    //显示的实际imageView中图片的高度
    CGFloat showHeight = ( self.transformImage.size.height * self.editImaegView.frame.size.width ) / self.transformImage.size.width;
    //上下留白高度
    CGFloat topBottomSpace = (self.editImaegView.frame.size.height - showHeight) / 2;
    
    CGRect originalRect = self.coverView.holeRect;

    CGRect toRect = CGRectMake(originalRect.origin.x * scale, (originalRect.origin.y - topBottomSpace) * scale + topBottomSpace, originalRect.size.width * scale, originalRect.size.height * scale);

    resultVC.resultImage = [self takeScreenShotImage:self.transformImage withRect:toRect orientation:self.transformImage.imageOrientation];
    [self.navigationController pushViewController:resultVC animated:YES];
}
- (void)clickRotateBtn{
    NSLog(@"transform");
    switch (currentRotate) {
        case UIImageOrientationUp:
            currentRotate = UIImageOrientationRight;
            break;
        case UIImageOrientationDown:
            currentRotate = UIImageOrientationLeft;
            break;
        case UIImageOrientationRight:
            currentRotate = UIImageOrientationDown;
            break;
        case UIImageOrientationLeft:
            currentRotate = UIImageOrientationUp;
            break;
        default:
            break;
    }
    self.transformImage = [[UIImage alloc] initWithCGImage:[self.transformImage CGImage] scale:1.0 orientation:currentRotate];
    [self.editImaegView setImage:self.transformImage];
}
#pragma mark-
- (UIImage *)fixrotation:(UIImage *)image{
    
    
    if (image.imageOrientation == UIImageOrientationUp) return image;
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (image.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, image.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (image.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                                             CGImageGetBitsPerComponent(image.CGImage), 0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
    
}
#pragma mark-
- (UIImage*)takeScreenShot:(UIView*)currentView withRect:(CGRect)rect{
    UIGraphicsBeginImageContext(currentView.frame.size);
    [currentView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIImage *resultImg = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, rect)];
    UIGraphicsEndImageContext();
    return resultImg;
}
- (UIImage*)takeScreenShotImage:(UIImage*)currentImage withRect:(CGRect)rect orientation:(UIImageOrientation) orientation{
    
    UIGraphicsBeginImageContext(currentImage.size);
    UIImage *resultImg = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(currentImage.CGImage, rect)scale:1.0 orientation:orientation];
    
    UIGraphicsEndImageContext();
    
    return resultImg;
}
#pragma mark-
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
